//! ## Helper functions for calling libc functions
//!
//! This module provides a few helper functions for calling libc functions and checking
//! their return values.
//! - `check!`: This macro checks the return value of the expression and returns an error
//!   if it is negative.

/// Check the return value of a libc function.
macro_rules! check {
    (
        $ex:expr $(;
            match $pat:pat $(if $cond:expr)? => $action:expr
        )* $(;
            else $clean:block
        )?
    ) => {{
        let __ret = $ex;
        let __res: $crate::error::Result<()> = if (__ret as isize) < 0 {
            // Safety: `__errno_location` returns a valid pointer to the thread-local
            // `errno`.
            let errno = *libc::__errno_location();
            Err($crate::error::Error::LibcError { errno })
        } else {
            Ok(())
        };
        match __res {
            Ok(_) => __ret,
            $($pat $(if $cond)? => $action,)*
            Err(e) => {
                $($clean)?
                return Err(e);
            }
        }
    }};
}
pub(crate) use check;
